package com.mkyong.common.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;

import com.mkyong.common.domain.Employee;
import com.mkyong.common.domain.Department;

public class JpaTest {

//	private EntityManager manager;
//
//	public JpaTest(EntityManager manager) {
//		this.manager = manager;
//	}
	/**
	 * @param args
	 */
	
	@PersistenceContext
	private static  EntityManager em;

	public EntityManager getEm() {
		return em;
	}

	public void setEm(EntityManager em) {
		this.em = em;
	}
	
	
	public static void main(String[] args) {
	//	EntityManagerFactory factory = Persistence.createEntityManagerFactory("persistenceUnit");
	//	EntityManager manager = factory.createEntityManager();
		JpaTest test = new JpaTest();
										
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		try {
			test.createEmployees();
		} catch (Exception e) {
			e.printStackTrace();
		}
		tx.commit();

		test.listEmployees();

		System.out.println(".. done");
	}




	private void createEmployees() {
		int numOfEmployees = em.createQuery("Select a From Employee a").getResultList().size();
		if (numOfEmployees == 0) {
			Department department = new Department("java");
			em.persist(department);

			em.persist(new Employee("Jakab Gipsz",department));
			em.persist(new Employee("Captain Nemo",department));

		}
	}

	@SuppressWarnings("unchecked")
	private void listEmployees() {
		
		List<Employee> resultList = em.createQuery("Select a From Employee a").getResultList();
		System.out.println("num of employess:" + resultList.size());
		for (Employee next : resultList) {
			System.out.println("next employee: " + next);
		}
	}


}
